<template>
  <el-container>
    <el-card shadow="always" class="box-card">
        <div slot="header" style="margin-top: 5px;margin-bottom: 5px">
            <el-text ><b>{{liveData.title}}</b></el-text>
            <el-text type="info" size="small" style="margin-left: 10px">{{liveData.detail}}</el-text>
        </div>

        <div id="dplayer" style="width: 100%;height: 100%"></div>

        <!--叠加的观众水印信息-->
        <div id="audience-water" style="width: 100%"></div>

        <!--叠加的直播会场水印信息-->
        <div id="meeting-water" class="dplayer-info-panel" style="display: none;right: 10px;left: initial">
            <div class="dplayer-info-panel-item" v-show="liveData.waterName">
<!--                <span class="dplayer-info-panel-item-title">会场名</span>-->
                <span class="dplayer-info-panel-item-data">{{liveData.waterName}}</span>
            </div>
            <!--          <div class="dplayer-info-panel-item" v-show="liveData.waterTime && liveData.waterTime === 1">-->
            <!--            <span class="dplayer-info-panel-item-title">时间</span>-->
            <!--            <span class="dplayer-info-panel-item-data">{{nowTime}}</span>-->
            <!--          </div>-->
        </div>
    </el-card>

<!--    TOFIX: dialog遮罩加深-->
    <el-dialog title="观众信息" custom-class="custom-dialog" v-model="audienceOpen" append-to-body style="z-index: 9990;width: 50%" :show-close="false" :close-on-click-modal="false">
        <el-form ref="audienceRef" :model="audienceForm" :rules="audienceRules">
            <el-form-item label="姓名" prop="name" v-if="isShowField('name')">
                <el-input v-model="audienceForm.name" placeholder="请输入姓名"/>
            </el-form-item>
            <el-form-item label="电话" prop="phone" v-if="isShowField('phone')">
                <el-input v-model="audienceForm.phone" placeholder="请输入电话" />
            </el-form-item>
            <el-form-item label="单位" prop="unit" v-if="isShowField('unit')">
                <el-input v-model="audienceForm.unit" placeholder="请输入单位" />
            </el-form-item>
            <el-form-item label="部门" prop="department" v-if="isShowField('department')">
                <el-input v-model="audienceForm.department" placeholder="请输入部门" />
            </el-form-item>
            <el-form-item label="职务" prop="position" v-if="isShowField('department')">
                <el-input v-model="audienceForm.position" placeholder="请输入职务" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email" v-if="isShowField('email')">
                <el-input v-model="audienceForm.email" placeholder="请输入邮箱" />
            </el-form-item>
            <el-form-item label="性别" prop="gender" v-if="isShowField('gender')">
                <el-input v-model="audienceForm.gender" placeholder="请输入性别" />
            </el-form-item>
            <el-form-item label="QQ" prop="qq" v-if="isShowField('qq')">
                <el-input v-model="audienceForm.qq" placeholder="请输入QQ" />
            </el-form-item>
            <el-form-item label="WX" prop="wx" v-if="isShowField('wx')">
                <el-input v-model="audienceForm.wx" placeholder="请输入微信" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="submitAudienceForm">确 定</el-button>
<!--                <el-button @click="cancelAudienceForm">取 消</el-button>-->
            </div>
        </template>
    </el-dialog>

    <FullScreenLock :isLocked="isLocked" @unlocked="handleUnlocked"  :correctPassword="correctPassword" />
  </el-container>
</template>

<style scoped>
.box-card {
  width: 100%;
}

:deep(.dplayer-menu > *:nth-last-child(1)) {
  display: none;
}
:deep(.dplayer-menu > *:nth-last-child(2)) {
  display: none;
}
:deep(.el-card__body) {
  padding: 5px !important
}
:deep(.dplayer-logo) {
  width: 50px;
  height: 50px;
}
:deep(.dplayer-logo img) {
  width: 100%;
  height: 100%;
  border-radius: 50%;
}
:deep(.dplayer-info-panel) {
  width: initial;
}
:deep(.dplayer-info-panel .dplayer-info-panel-item-data) {
  width: initial;
}
:deep(.dplayer-info-panel-item .dplayer-info-panel-item-url) {
  width: 400px;
}

:deep(.el-overlay) {
    background-color: rgba(0, 0, 0, 0.8) !important;
}
</style>

<script setup>
import Hls from "hls.js";
import DPlayer from 'dplayer';
import {onMounted, ref} from "vue";
import { useRoute } from 'vue-router';
import {addLive, getLive, updateLive, updateViewCount} from "@/api/live.js";
import {getAudienceSetting} from "@/api/audienceSetting.js";
import {addAudience} from "@/api/audience.js";
import FullScreenLock from '@/components/FullScreenLock';
import {removeWatermark, setMeetingWaterMark, setWaterMark} from '@/utils/watermark';
const { proxy } = getCurrentInstance();

defineOptions({
  name: "Live"
});

const baseUrl = import.meta.env.VITE_APP_BASE_API;

const data = reactive({
    liveData: {},
    audienceRules: {
        name: [
            { required: true, message: "请输入姓名", trigger: "blur" }
        ],
        phone: [
            { required: true, message: "请输入电话", trigger: "blur" }
        ],
        unit: [
            { required: true, message: "请输入单位", trigger: "blur" }
        ],
        department: [
            { required: true, message: "请输入部门", trigger: "blur" }
        ],
        position: [
            { required: true, message: "请输入职务", trigger: "blur" }
        ],
        email: [
            { required: true, message: "请输入邮箱", trigger: "blur" }
        ],
        gender: [
            { required: true, message: "请输入性别", trigger: "blur" }
        ],
        qq: [
            { required: true, message: "请输入QQ", trigger: "blur" }
        ],
        wx: [
            { required: true, message: "请输入微信", trigger: "blur" }
        ]
    }
});
const { liveData, audienceRules } = toRefs(data);

/**
 * 密码锁屏处理
 */
const isLocked = ref(false);
const correctPassword = ref('');
function handleUnlocked() {
    isLocked.value = false;
    showAudienceForm();
}

/**
 * 获取当前直播数据
 * @type {RouteLocationNormalizedLoaded}
 */
const route = useRoute();
const liveId = route.query.id;

/**
 * 初始创建直播组件
 * @type {null}
 */
let dp = null
onMounted(() => {
  initAudienceSetting();

  getLive(liveId).then((res) => {
    if(!res.data) {
      proxy.$modal.msgError("直播不存在");
      return;
    }

    liveData.value = res.data;
    if(liveData.value.password && liveData.value.password !== '') {
        isLocked.value = true;
        correctPassword.value = liveData.value.password;
    } else {
        isLocked.value = false;
        showAudienceForm();
    }
    // 更新观看次数
    updateVisitCount();
    initLive();
  });
})

// 监听isLocked变化
// watch(isLocked, (newValue, oldValue) => {
//     if(newValue === false && oldValue === true) {
//         showAudienceForm();
//     }
// })

/**
 * 更新观看次数
 */
function updateVisitCount() {
  const params = {
    id: liveId
  }
  updateViewCount(params);
}


/**
 * 观众信息采集窗口
 */
const audienceOpen = ref(false);
const audienceForm = ref({});
const audienceSetting = ref({});

function showAudienceForm() {
    if(!audienceSetting.value.needFields || audienceSetting.value.needFields === '') {
        audienceOpen.value = false;
    } else {
        audienceOpen.value = true;
    }
}
function submitAudienceForm() {
    proxy.$refs["audienceRef"].validate(valid => {
        if (valid) {
            proxy.$modal.confirm('确认提交？').then(function() {
                audienceForm.value.liveId = liveId;
                addAudience(audienceForm.value).then(response => {
                    proxy.$modal.msgSuccess("提交成功");
                    audienceOpen.value = false;
                });
            });
        }
    });
}

// function reset() {
//     audienceForm.value = {};
//     proxy.resetForm("audienceRef");
// }

// function cancelAudienceForm() {
//     audienceOpen.value = false;
// }
async function initAudienceSetting() {
    let res = await getAudienceSetting(liveId);
    if(!res.data) {
      return;
    }
    audienceSetting.value = res.data;
}
function isShowField(field) {
    if(!audienceSetting.value.needFields || audienceSetting.value.needFields === '') {
      return false;
    }
    return audienceSetting.value.needFields.indexOf(field) !== -1;
}

function addWatermarks(audienceSetting, audienceForm, waterMarks) {
    if(!audienceSetting.value.waterFields && audienceSetting.value.waterFields === '') {
        return
    }
    const  waterFieldsArr = audienceSetting.value.waterFields.split(',');
    waterFieldsArr.forEach(field => {
        if (audienceForm.value[field] && audienceForm.value[field] !== '') {
            waterMarks.push(audienceForm.value[field]);
        }
    });
}

/**
}

/**
 * 初始化直播
 * @type {null}
 */

let waterMarkInterval = null;

const initLive = () => {
    let logo = baseUrl + liveData.value.waterLogo;
    if(!liveData.value.waterLogo || liveData.value.waterLogo === '') {
        logo = "";
    }
  dp = new DPlayer({
    container: document.getElementById('dplayer'),
    live: true,
    theme: '#13CBD3',
    logo: logo, //直播水印台标
    video: {
      url: liveData.value.pullUrl,
      type: 'customHls',
      customType: {
        customHls: function (video, player) {
          const hls = new Hls();
          hls.loadSource(video.src);
          hls.attachMedia(video);
        },
      }
    }
  });

  /**
   * 在监听视频播放的时候设置水印
   */
  dp.on('play', function () {
    if (waterMarkInterval) {
      clearInterval(waterMarkInterval);
    }

    // let page = document.getElementById('audience-water');
    // setWaterMark(`测试水印`, "时间", page, true);

    let waterMarks = [];
    addWatermarks(audienceSetting, audienceForm, waterMarks);

    if(waterMarks.length > 0) {
      waterMarkInterval = setInterval(() => {
        let page = document.getElementById('audience-water');
        // let waterMarks = ["测试水印","哈哈哈哈","哦哦哦"]
        setWaterMark(waterMarks, page, true);
        setTimeout(() => {
          removeWatermark();
        }, 3000); //每次水印维持3秒后去除
      }, 4000); //4秒显示一次
    }

    if(liveData.value.waterName && liveData.value.waterName !== '') {
      setMeetingWaterMark("meeting-water");
    }
  })

  dp.on('pause', function () {
    if (waterMark) {
      clearInterval(vm.WaterMark);
    }
  });
}

/**
 * 停止直播
 */
const stopLive = () => {
  dp&&dp.pause();
}



</script>
